package com.dems.dao.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Objects;

@Configuration
@MapperScan(basePackages = LaDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "laSqlSessionFactory", sqlSessionTemplateRef = "laSqlSessionTemplate")
public class LaDataBaseConfig {

    private DataSource laDataSource;
    static final String PACKAGE = "com.dems.dao.mapper.la";
    //没用到mapper的xml所以可以不用配置
    static final String LOCATION = "classpath*:mapper/la/*xml";

    public LaDataBaseConfig(@Qualifier("laDataSource") DataSource laDataSource){
        this.laDataSource=laDataSource;
    }

    @Bean
    @Primary
    public MybatisSqlSessionFactoryBean laSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(laDataSource);
        sessionFactoryBean.setPlugins(laMybatisPlusInterceptor());
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(LaDataBaseConfig.LOCATION));
        return sessionFactoryBean;
    }

    @Bean
    @Primary
    public SqlSessionTemplate laSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(Objects.requireNonNull(laSqlSessionFactory().getObject()));
    }

    @Bean
    @Primary
    public MybatisPlusInterceptor laMybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}
